/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.autosalon.ui.automobil.action;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.autosalon.DAO.DaoFactory;
import com.autosalon.model.Doplnek;
import com.autosalon.model.Model;
import com.autosalon.tools.Constants;
import com.autosalon.ui.automobil.Automobil;
import com.autosalon.ui.automobil.state.AutomobilStateHolder;
import com.vaadin.ui.Button.ClickEvent;

/**
 *  Trida slouzici k ulozeni automobilu do databaze
 * @author Petr Kriegisch
 */
public class SaveAutomobilAction extends AbstractAutomobilAction {

    com.autosalon.model.Automobil auto;
    List<Doplnek> doplnky;

    public SaveAutomobilAction(Automobil automobil) {
        super(automobil);
    }

    @Override
    public void buttonClick(ClickEvent event) {
        try {
            doplnky = new ArrayList<Doplnek>();
            auto = new com.autosalon.model.Automobil();
            Model model = (Model) DaoFactory.getinstance().getModel().getOneByParam(Constants.DB_MODEL_NAZEV_MODELU, automobil.getCbModel().getValue());
            auto.setModel(model);
            auto.setCena(Integer.parseInt(automobil.getLblCena().getValue().toString()));
            Date d = new Date();
            d = (Date) automobil.getPdDatum().getValue();
            auto.setDatumVyroby(new java.sql.Date(d.getTime()));
            auto.setNajeto(Integer.parseInt(automobil.getLblKm().getValue().toString()));
            Set<String> vybranaVybava = new HashSet<String>((Collection) automobil.getTsVybava().getValue());
            for (String string : vybranaVybava) {
                doplnky.add((Doplnek) (DaoFactory.getinstance().getDoplnek().getOneByParam(Constants.DB_DOPLNEK_POPIS_DOPLNKU, string)));
            }
            auto.setZakladni_vybava(doplnky);


            DaoFactory.getinstance().getAutomobil().insert(auto);

            automobil.getWindow().showNotification("Ulozeni probehlo uspesne");
            // automobil.initFormNewCar();
            int id;
            try {
                id = automobil.getSwitcher().getMainWindow().getZakaznik().getRole().getId().intValue();
            } catch (NullPointerException e) {
                id = 1;
            }
            automobil.naplneniVsechTabulek();


            AutomobilStateHolder.setState(AutomobilStateHolder.VIEW_AUTOMOBIL_STATE, id, automobil);
        } catch (NumberFormatException e) {
            automobil.getWindow().showNotification("Vlozene udaje jsou chybne");
        } catch (IndexOutOfBoundsException in) {
            automobil.getWindow().showNotification("Vlozene udaje jsou chybne");
        } catch (NullPointerException np) {
            automobil.getWindow().showNotification("Vlozene udaje jsou chybne");
        }
    }
}
